/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.core.factory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * A generic registry for objects. The objects can be retrieved by NAME or by CLASSNAME.
 * The class name is the fully (package) qualified name of the objects class. For the implementations that ship with
 * jbfilter, the providers are registered by the name which is the third part of the package name :
 * org.jbfilter.bean --> bean, org.jbfilter.hibernate --> hibernate...
 * @author Marcus Adrian
 */
public abstract class GenericRegistry<T> {
	private Map<String, T> byName = new HashMap<String, T>();
	private Map<String, T> byClassName = new HashMap<String, T>();
	
	/**
	 * Retrieve the object by NAME. See explanations on class comment.
	 * @param name the name, i.e. "bean", "hibernate", "jpa"...
	 * @return
	 */
	public T fromName(String name) {
		T found = byName.get(name);
		if (found != null) {
			return found;
		}
		return fromNameFirstTime(name);
	}
	/**
	 * Retrieve the object by CLASSNAME. See explanations on class comment.
	 * Note that the objects that ship with the jbfilter libraries are NOT registered by CLASSNAME.
	 * Use {@link #fromName(String)} to retrieve them by NAME. Or register them manually with {@link #register(T)} if
	 * you really must retrieve them by CLASSNAME.
	 * @param className the fully (package) qualified name of the object class
	 * @return
	 */
	public T fromClassName(String className) {
		T found = byClassName.get(className);
		if (found != null) {
			return found;
		}
		return fromClassNameFirstTime(className);
	}
	private T fromNameFirstTime(String name) {
		synchronized (byName) {
			T found = byName.get(name);
			if (found != null) {
				return found;
			}
			String className = getClassNameFromName(name);
			try {
				Class<?> factoryClass = Class.forName(className);
				Method method = factoryClass.getMethod("getProvider");
				@SuppressWarnings("unchecked")
				T invoke = (T)method.invoke(null);
				register(name, invoke);
				return byName.get(name);
			} catch (Exception e) {
				throw new RuntimeException(String.format("No provider class registered for '%s' in registry %s.", name, getClass().getName()), e);
			}
		}
	}
	/**
	 * Of course at the end we need a class name to instantiate an object.
	 * This method specifies the mechanism for retrieving the class name from the NAME.
	 * @param name
	 * @return
	 */
	protected abstract String getClassNameFromName(String name);
	
	private T fromClassNameFirstTime(String className) {
		synchronized (byClassName) {
			T found = byClassName.get(className);
			if (found != null) {
				return found;
			}
			try {
				@SuppressWarnings("unchecked")
				T newInstance = (T)Class.forName(className).newInstance();
				register(newInstance);
				return byClassName.get(className);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	/**
	 * Register by NAME.
	 * @param name the name used to retrieve the object later
	 * @param t the object to register
	 */
	public void register(String name, T t) {
		byName.put(name, t);
	}
	/**
	 * Register by CLASSNAME.
	 * @param t the object to register
	 */
	public void register(T t) {
		byClassName.put(t.getClass().getName(), t);
	}
	
}
